package com.yupi.springbootinit.bimq;

import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.constant.MqConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class BiDeadConsumer {
    @Resource
    private ChartService chartService;

    @Resource
    private AiManager aiManager;

    @SneakyThrows
    @RabbitListener(queues = {MqConstant.DEAD_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTage){
        log.info("死信队列已接受到消息 tag ：" + deliveryTage + "消息内容是" +  message);
        if(StringUtils.isBlank(message)){
            channel.basicNack(deliveryTage, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }

        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if(chart == null){
            channel.basicNack(deliveryTage, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图表为空");
        }

        // 处理死信消息直接将状态设置为 failed
        Chart updateChartStatus = new Chart();
        updateChartStatus.setId(chartId);
        updateChartStatus.setStatus("failed");
        boolean updateResult = chartService.updateById(updateChartStatus);
        if(!updateResult){
            chartService.handleChartUpdateError(chartId, "更新图表状态时发生异常");
        }

        log.info("死信队列已消费消息 tag ：" + deliveryTage + ", 的消息，消息内容为" + chartId);
        channel.basicAck(deliveryTage, false);
    }
}
